package hkr.test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.security.PublicKey;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeoutException;

import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.util.Log;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class MainActivity extends Activity {
	
	private Camera camera;
	private SurfaceHolder previewHolder;
	private boolean resumedWithoutFocus;
	private boolean focused;
	private PowerManager.WakeLock wl;
	
	
	PictureCallback pictureCallback = new PictureCallback() {

		@Override
		public void onPictureTaken(byte[] arg0, Camera arg1) {
			Log.d("test", "picture taken");
			File file = getOutputMediaFile();
			FileOutputStream fos;
			try {
				fos = new FileOutputStream(file);
				fos.write(arg0);												
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException ioe) {
				// TODO Auto-generated catch block
				ioe.printStackTrace();
			}
			camera.startPreview();
			
			Log.d("test", "takin pic");
			camera.takePicture(null, null, pictureCallback);
		}
	};
	
	private void startRecording() {
		
		Log.e("start","start");
		camera = Camera.open();
		if (camera != null && previewHolder != null && previewHolder.getSurface() != null) {
			if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
				camera.setDisplayOrientation(90);
			else // ORIENTATION_LANDSCAPE
				camera.setDisplayOrientation(0);			
						
			try {
				camera.setPreviewDisplay(previewHolder);
			}
			catch (IOException e) {
				e.printStackTrace();
			}
			camera.startPreview();
			camera.takePicture(null, null, pictureCallback);
		}
	}
	
	public void stopRecording() {
		if (camera != null) {
		    camera.release();
		    camera = null;
		}
	}
	
	@SuppressLint("SimpleDateFormat")
	public static File getOutputMediaFile() {
		File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "test");
		
		if (!mediaStorageDir.exists()) {
			if (!mediaStorageDir.mkdirs()) {
				Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
	    // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + "IMG_" + timeStamp + ".jpg");
        return mediaFile;
	}
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
		wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "Keeps the screen bright");
		//wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "Dims instead of sleep");
		SurfaceView preview = (SurfaceView) findViewById(R.id.surfaceView1);
		previewHolder = preview.getHolder();
	}

	@Override
	public void onResume() {	
		super.onResume();	
		wl.acquire();
		if (focused == false)
			resumedWithoutFocus = true;
		else // never happens
			this.startRecording();
	}
	
	@Override
	public void onWindowFocusChanged(boolean focused) {
		super.onWindowFocusChanged(focused);	  	
		this.focused = focused;
		if (resumedWithoutFocus && focused) {
			this.startRecording();
			resumedWithoutFocus = false;
		}
	}
	
	@Override
	public void onPause() {
		super.onPause();
		stopRecording();
		wl.release();
	}
}
